﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Opossum : MonoBehaviour
{
    public Rigidbody2D rb;
    public LayerMask groundLayer;
    public Vector2 direction;
    public float moveSpeed = 10f;
    public float hits_border_distance = 0.5f;
    public float hits_collision_distance = 0.1f;
    public float waitSecond = 0.1f;

    public bool isPlay = true;
    public bool isDead = false;
    void Start()
    {
        direction = Vector2.left;
        SetFace();
    }
    
    void Update()
    {
        if (isDead == true)
        {
            return;
        }

        if (isPlay)
        {
            Movement();

            RaycastHit2D[] hits_border = ShuaiFunctions.RaycastAll(transform.position, new Vector2(hits_border_distance * direction.x, 0), Vector2.down, 1, groundLayer, Color.red);
            if (hits_border.Length == 0)
            {
                StartCoroutine(WaitFlip(waitSecond));
            }
            
            RaycastHit2D[] hits_collision = ShuaiFunctions.RaycastAll(transform.position, Vector2.zero, direction, hits_collision_distance, groundLayer, Color.green);
            if (hits_collision.Length > 0)
            {
                StartCoroutine(WaitFlip(waitSecond));
            }
        }
    }

    IEnumerator WaitFlip(float t)
    {
        isPlay = false;
        yield return new WaitForSeconds(t);//运行到这，暂停t秒

        Flip();
        isPlay = true;
    }

    public void Movement()
    {
        rb.velocity = new Vector2(moveSpeed * direction.x, rb.velocity.y);
    }

    public void Flip()
    {
        direction = -direction;
        SetFace();
    }

    public void SetFace()
    {
        Vector3 theScale = transform.localScale;
        theScale.x = direction.x * -1;
        transform.localScale = theScale;
    }

    public void Dead()
    {
        RaycastHit2D[] hits_down = ShuaiFunctions.RaycastAll(transform.position, Vector2.zero, Vector2.down, 1, groundLayer, Color.red); //长度1的射线
        if (hits_down.Length >= 1)
        {
            Block block = hits_down[0].collider.gameObject.GetComponent<Block>();
            Debug.Log(block);
            block.Dead();
        }

        Collider2D coll = GetComponent<Collider2D>();
        coll.isTrigger = true;
        rb.velocity = Vector2.zero;
        isPlay = false;
        isDead = true;
    }
    
}
